import { Injectable, OnModuleInit } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AreaEntity } from "../entities/area.entity";

@Injectable()
export class AreaService implements OnModuleInit {
  constructor(
    @InjectRepository(AreaEntity)
    private readonly areaRepo: Repository<AreaEntity>
  ) {}

  async onModuleInit(): Promise<void> {
    // 初始化基础数据（幂等）
    const seeds: Partial<AreaEntity>[] = [
      {
        name: "铁索连舟【新】",
        style: 15,
        state: 0,
        mod_dstid: "ws://cd521.xin:8206/user-service/websocket",
        descr: " ",
        ol_count: 0,
        order_lvl: 23,
        ol_limit: 1000,
        socket_port: 8206000,
        socket_ip: "",
      },
      {
        name: "草船借箭",
        style: 15,
        state: 0,
        mod_dstid: "ws://cd521.xin:8209/user-service/websocket",
        descr: " ",
        ol_count: 0,
        order_lvl: 22,
        ol_limit: 1000,
        socket_port: 82061,
        socket_ip: "",
      },
      {
        name: "三顾茅庐",
        style: 15,
        state: 0,
        mod_dstid: "ws://cd521.xin:8208/user-service/websocket",
        descr: " ",
        ol_count: 0,
        order_lvl: 17,
        ol_limit: 1000,
        socket_port: 8208,
        socket_ip: " ",
      },
      {
        name: "桃园结义",
        style: 15,
        state: 0,
        mod_dstid: "ws://cd521.xin:8207/user-service/websocket",
        descr: " ",
        ol_count: 0,
        order_lvl: 12,
        ol_limit: 600,
        socket_port: 8207,
        socket_ip: "111.13.52.47",
      },
    ];
    for (const a of seeds) {
      const exist = await this.areaRepo.findOne({ where: { name: a.name } });
      if (!exist) {
        await this.areaRepo.save(a);
      }
    }
  }

  async list(): Promise<AreaEntity[]> {
    return this.areaRepo.find({ order: { order_lvl: "DESC" } });
  }
}
